<template>
  <div style="padding: 0 15px;">

    <div class="box">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <h3 style="line-height: 32px">
              SKU管理
            </h3>
          </div>
        </el-col>
        <el-col :span="16" style="text-align: right">
          <div class="grid-content bg-purple">
            <el-button
              size="small"
              type="primary"
              icon="el-icon-circle-plus-outline"
              @click="showAddSkuDialog"
            >
              新增SKU
            </el-button>

            <el-button
              size="small"
              type="primary"
              icon="el-icon-refresh-left"
              @click="handleStockSynchronise"
            >
              同步SPU库存
            </el-button>

            <el-button
              size="small"
              type="primary"
              icon="el-icon-refresh-left"
              @click="handlePriceSynchronise"
            >
              同步SPU价格
            </el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-table
      ref="multipleTable"
      border
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column align="center" label="编号" width="100">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center" label="标题">
        <template slot-scope="scope">{{ scope.row.title }}</template>
      </el-table-column>
      <el-table-column align="center" label="售价" width="120">
        <template slot-scope="scope">{{ scope.row.price }}</template>
      </el-table-column>

      <!-- 动态加载SKU，显示操作列 -->
      <el-table-column
        v-for="(item, i) in attrList"
        :key="i"
        align="center"
        :label="item.name"
      >
        <template slot-scope="scope">{{
          scope.row.specifications[i].attributeValue
        }}</template>
      </el-table-column>

      <el-table-column align="center" label="库存" width="120">
        <template slot-scope="scope">{{ scope.row.stock }}</template>
      </el-table-column>
      <el-table-column align="center" label="库存预警值" width="120">
        <template slot-scope="scope">{{ scope.row.stockThreshold }}</template>
      </el-table-column>

      <el-table-column align="center" label="排序" width="80">
        <template slot-scope="scope">{{ scope.row.sort }}</template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="100">
        <template slot-scope="scope">
          <!-- <el-button
            title="编辑"
            type="warning"
            size="mini"
            icon="el-icon-edit"
            circle
            @click="$router.push('#' + scope.row.id)"
          ></el-button> -->
          <el-button
            title="删除"
            type="danger"
            size="mini"
            icon="el-icon-delete"
            circle
            @click="$router.push('#' + scope.row.id)"
          />
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        :current-page="currentPage"
        layout="total, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增SKU的弹窗 -->
    <el-dialog
      title="新增SKU"
      :visible.sync="addDialogVisible"
      :modal-append-to-body="false"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="130px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="16">
            <el-form-item label="SKU标题" prop="title">
              <el-input
                v-model="ruleForm.title"
                size="small"
                placeholder="请输入SKU标题"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 单选按钮属性模板 -->
        <el-row v-for="(item, i) in attrList" :key="i">
          <el-form-item
            v-if="item.inputType == 1"
            :label="item.name"
            :prop="item.name"
          >
            <el-radio-group v-model="selectedAttrList[item.name]">
              <el-radio
                v-for="(val, j) in item.valueList.split(',')"
                :key="j"
                :label="val"
              >
                {{ val }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 复选框属性模板 -->
          <el-form-item
            v-if="item.inputType == 2"
            :label="item.name"
            :prop="item.name"
          >
            <el-checkbox-group v-model="selectedAttrList[item.name]">
              <el-checkbox
                v-for="(opt, j) in item.valueList.split(',')"
                :key="j"
                :label="opt"
              >
                {{ opt }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="16">
            <el-form-item label="价格" prop="price">
              <el-input
                v-model="ruleForm.price"
                size="small"
                placeholder="请输入价格"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16">
            <el-form-item label="当前库存" prop="stock">
              <el-input v-model="ruleForm.stock" placeholder="请输入当前库存" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16">
            <el-form-item label="库存预警阈值" prop="stockThreshold">
              <el-input
                v-model="ruleForm.stockThreshold"
                placeholder="请输入库存预警阈值"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16">
            <el-form-item label="排序序号" prop="sort">
              <el-input
                v-model="ruleForm.sort"
                placeholder="序号值越大，越靠前"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="20">
            <el-form-item label="选择图片" prop="selectedPicList">
              <el-checkbox-group v-model="ruleForm.selectedPicList">
                <el-checkbox
                  v-for="(item, i) in spuPicList"
                  :key="i"
                  class="pic_checkbox"
                  :label="item.url"
                  border
                >
                  <img width="30px" height="30px" :src="item.url" alt="">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('ruleForm')"
          >确认新增SKU</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentSpu: {}, // 保存当前Spu
      addDialogVisible: false, // 新增SKU弹窗是否显示
      attrList: [], // 描述当前模板包含的所有属性列表
      selectedAttrList: [], // 描述用户选中的sku属性列表
      spuPicList: [], // 描述当前SPU包含的图片列表
      currentPage: 1, // 表示当前页码
      pageSize: 5, // 表示每页多少条
      total: 1, // 表示总条目数

      ruleForm: {
        // 描述选中的图片列表
        selectedPicList: []
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        stock: [{ required: true, message: '请选择库存数量', trigger: 'blur' }],
        stockThreshold: [
          { required: true, message: '请输入库存警戒阈值', trigger: 'blur' }
        ]
      },
      input: '',

      tableData: [
        {
          id: '01',
          image: '/favicon.ico',
          name: '王小虎商品 王小虎商品 王小虎商品 ',
          price: 6222,
          isSJ: true,
          isTJ: true,
          isXP: true,
          sorts: 99,
          state: 1,
          salenum: 999,
          skunum: 299,
          shstate: 1
        },
        {
          id: '01',
          image: '/favicon.ico',
          name: '王小虎商品 王小虎商品 王小虎商品 ',
          price: 6212,
          isSJ: true,
          isTJ: true,
          isXP: true,
          sorts: 99,
          state: 1,
          salenum: 999,
          skunum: 299,
          shstate: 1
        },
        {
          id: '01',
          image: '/favicon.ico',
          name: '王小虎商品 王小虎商品 王小虎商品 ',
          price: 6122,
          isSJ: true,
          isTJ: true,
          isXP: true,
          sorts: 99,
          state: 1,
          salenum: 999,
          skunum: 299,
          shstate: 1
        },
        {
          id: '01',
          image: '/favicon.ico',
          name: '王小虎商品 王小虎商品 王小虎商品 ',
          price: 1222,
          isSJ: true,
          isTJ: true,
          isXP: true,
          sorts: 99,
          state: 1,
          salenum: 999,
          skunum: 299,
          shstate: 1
        }
      ],
      multipleSelection: []
    }
  },

  mounted() {
    const spuId = this.$route.params.id
    this.currentSpu.id = spuId
    console.log(spuId)
    // 通过spuId查询详情
    this.spuApi.queryById({ id: spuId }).then((res) => {
      console.log('查询spu详情', res)
      if (res.data.state === 200) {
        this.currentSpu = res.data.data
        // 根据albumId查询SPU图片列表，供新增SKU时选择
        this.queryPicsByAlbumId(this.currentSpu.albumId)
        // 根据模板ID查询销售属性列表
        this.querySalesByTemplateId(this.currentSpu.attributeTemplateId)
      } else {
        this.$alert(res.data.message, '提示')
      }
    })

    // 根据spuID 查询SKU列表
    this.querySkuList()
  },

  methods: {

    /**
     * 同步SPU库存
     */
    handleStockSynchronise() {
      const id = this.currentSpu.id
      this.spuApi.synchroniseStock({ id }).then(res => {
        console.log('同步SPU库存', res)
        if (res.data.state === 200) {
          this.$alert('同步SPU库存完成', '提示')
        } else {
          this.$alert(res.data.message, '提示')
        }
      })
    },

    /**
     * 同步SPU价格
     */
    handlePriceSynchronise() {
      const id = this.currentSpu.id
      this.spuApi.synchronisePrice({ id }).then(res => {
        console.log('同步SPU价格', res)
        if (res.data.state === 200) {
          this.$alert('同步SPU价格完成', '提示')
        } else {
          this.$alert(res.data.message, '提示')
        }
      })
    },

    // 根据spuId查询sku列表
    querySkuList() {
      const spuId = this.currentSpu.id
      const page = this.currentPage
      const pageSize = this.pageSize
      this.skuApi.queryBySpuId({ page, pageSize, spuId }).then((res) => {
        console.log('根据spuID查询sku列表', res)
        this.tableData = res.data.data.list
        this.total = res.data.data.total
      })
    },

    showAddSkuDialog() {
      // 初始化多选列表，否则checkbox无法完成数据绑定
      this.attrList.forEach((item) => {
        if (item.inputType === 2) {
          this.$set(this.selectedAttrList, item.name, [])
        }
      })
      this.addDialogVisible = true
    },

    queryPicsByAlbumId(albumId) {
      this.picturesApi.queryByAlbumId({ albumId }).then((res) => {
        console.log('根据AlbumId查询图片列表', res)
        if (res.data.state === 200) {
          this.spuPicList = res.data.data.list
        } else {
          this.$alert(res.data.message, '提示')
        }
      })
    },

    querySalesByTemplateId(templateId) {
      const page = 1
      const pageSize = 1000
      this.attributeApi
        .querySalesByTemplateId({ templateId, page, pageSize })
        .then((res) => {
          console.log('根据模板ID查询属性列表', res)
          this.attrList = res.data.data.list
        })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 补上参数specifications配置
          // 将specifications转成specificationArray数组格式
          // specifications:  {"附加商品":["配套彩笔"],"版本":"3本装","年龄段":"3~5岁"}
          // specificationArray: [
          //   { "attributeId":x,
          //     "attributeName":"附加商品",
          //     "attributeValue":"配套彩笔"
          //   }, .....]
          const specificationArray = []
          this.attrList.forEach((item) => {
            specificationArray.push({
              attributeId: item.id,
              attributeName: item.name,
              attributeValue: this.selectedAttrList[item.name].toString()
            })
          })
          this.ruleForm.specifications = JSON.stringify(specificationArray)
          // 补上参数pictures
          this.ruleForm.pictures = JSON.stringify(
            this.ruleForm.selectedPicList
          )
          // 补上albumId
          this.ruleForm.albumId = this.currentSpu.albumId
          // 补上spuId
          this.ruleForm.spuId = this.currentSpu.id
          // 补上templateId
          this.ruleForm.attributeTemplateId =
            this.currentSpu.attributeTemplateId
          console.log(this.ruleForm)
          // 发送请求，添加sku
          this.skuApi.add(this.ruleForm).then((res) => {
            console.log('添加sku结果', res)
            if (res.data.state === 200) {
              this.addDialogVisible = false
              this.$message({
                showClose: true,
                message: '恭喜你，新增SKU成功',
                type: 'success'
              })
              // 重新加载sku列表
              this.querySkuList()
            } else {
              this.$alert(res.data.message, '提示')
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    /** 处理更新页码后的业务 */
    handleCurrentChange(val) {
      console.log(`即将加载选中页: 第${val}页`)
      this.currentPage = val
      this.querySkuList()
    },

    handleSortChange(a, b) {
      return a.price - b.price
    },

    /** 删除SKU */
    deleteSku(id) {
      this.$confirm('确认删除该SKU?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 选择确认，执行删除业务
        this.skuApi.delete({ id: id }).then((res) => {
          console.log('删除Sku操作：', res)
          if (res.data.state === 200) {
            // 删除成功，重新加载Sku列表
            this.querySkuList()
          } else {
            this.$alert(res.data.message, '提示')
          }
        })
      })
    }
  }
}
</script>

<style scoped>
.el-checkbox.is-bordered {
  padding: 5px;
}
.el-checkbox.is-bordered >>> .el-checkbox__input {
  display: none;
}
.el-checkbox.is-bordered >>> .el-checkbox__label {
  padding: 0;
}
.pic_checkbox {
  margin-right: 5px !important;
  margin-left: 0px !important;
}
</style>
